<template>
  <div>
    <van-tabs>
      <van-tab title="表单信息">
        <div id="piqianGS">
          <div class="content">
            <img id="image" />
            <!--<img src={`data:;base64,${imgUrl}`}  />-->
            <div class="list">
              <van-form validate-first>
                <p class="subTitle"><span class="line"></span>规划批前公示</p>
                <div v-for="(item2, index2) in fileData" :key="index2 + 'fileData'"
                  style="line-height: 40px; border-bottom: 1px solid #9b9b9b">
                  <p style="font-size: 16px">
                    <span style="color: red" v-if="item2.isBitian">*</span>
                    {{ item2.name }}
                  </p>
                  <van-uploader @click-upload="getList(item2)" :after-read="afterRead" :before-delete="delectFile"
                    v-model="item2.fileList" multiple />
                </div>
                <div class="GSJL" style="border-bottom: 1px solid #9b9b9b; font-size: 16px">
                  <van-field readonly clickable required name="picker" :value="formData.GSJL | inUseName(CityColumns)"
                    label="公示结论" placeholder="请选择公示结论" @click="showPickerC = true"
                    style="font-size: 16px; text-align: right" />
                  <van-popup v-model="showPickerC" position="bottom" get-container="#popup">
                    <van-picker show-toolbar :columns="CityColumns" value-key="DICNAME" @confirm="onConfirmCity"
                      @cancel="showPickerC = false" />
                  </van-popup>
                </div>
                <div style="margin-top: 8px">
                  <span style="color: #ff0000">*</span>
                  <span style="font-size: 16px">公示意见</span>
                  <van-field v-model="formData.GSJG" type="textarea" label :border="false" disable-default-padding style="
                    background-color: #e4e4e4;
                    margin-top: 8px;
                    min-height: 140px;
                  " />
                </div>
              </van-form>
            </div>
          </div>
          <div class="footer">
            <!-- <van-button style="margin-right: 10px;" size="small" type="info" @click="getinsertDataView">提交</van-button> -->
            <van-button style="margin-right: 26px;width: 25vw;" size="small" type="info" @click="submit">提交</van-button>
            <van-button style="margin-right: 26px;width: 25vw;" size="small" type="info" @click="save">保存</van-button>
            <van-button style="margin-right: 10px;width: 25vw;" size="small" type="info" @click="Gotomap">地图</van-button>
          </div>
        </div>
      </van-tab>
      <van-tab title="过程信息">
        <FileData :ROW_GUID="rowData.ROW_GUID" :rowData="rowData"></FileData>
      </van-tab>
    </van-tabs>
  </div>
</template>

<script>
import {
  QuerySignCallback,
  dataTransFile,
  FileServerProxy,
  dataTransFilePreview,
  GetFileData,
} from "@/utils/api";
import FileData from '@/components/activity/FileData'
import { addDate, GSA_Search } from "../../common/commonApi";
export default {
  filters: {
    inUseName: function (msg, data) {
      let name = "";
      data.forEach((item) => {
        if (item.DICID == msg) {
          name = item.DICNAME;
        }
      });
      return name;
    },
  },
  data() {
    return {
      imgUrl: "",
      fileList: [],
      rowData: [],
      fileData: [
        {
          name: "规划批前公示远景照片",
          groupGuid: "2411faea-87d7-4754-98dd-8816c19d9909",
          fileList: [],
          isBitian: true
        },
        {
          name: "规划批前公示近景照片",
          groupGuid: "9a1d4f18-bbc2-474c-b029-c3dae700600d",
          fileList: [],
          isBitian: true
        },
      ],
      fwIdData: "",
      groupGuids: "",
      fileGuid: "",
      showPickerC: false,
      CityColumns: [],
      GSJG: "",
      GSJL: "",
      formData: {
        GSJL: "48",
        GSJG: "经七天公示，无异议",
        GSR: "",
        GSSJ: "",
        PKID: "",
      },
      NewSPYJLisyt: [],
      nowTime: "",
      isSave: true,
    };
  },
  watch: {},
  components: { FileData },
  computed: {},

  methods: {
    getList(item) {
      this.groupGuids = item.groupGuid;
    },
    getDiffDay(date_1, date_2) {
      // 计算两个日期之间的差值
      let totalDays, diffDate
      let myDate_1 = Date.parse(date_1)
      let myDate_2 = Date.parse(date_2)
      // 将两个日期都转换为毫秒格式，然后做差
      diffDate = Math.abs(myDate_1 - myDate_2) // 取相差毫秒数的绝对值
      totalDays = Math.floor(diffDate / (1000 * 3600 * 24)) // 向下取整
      // console.log(totalDays)    
      return totalDays    // 相差的天数
    },
    timestampToTime(times) {
      let time = times[1]
      let mdy = times[0]
      mdy = mdy.split('/')
      let month = parseInt(mdy[0]);
      let day = parseInt(mdy[1]);
      let year = parseInt(mdy[2])
      return year + '-' + month + '-' + day
    },
    async submit() {
      let me = this;
      //提交判断是否保存
      if (!this.formData.GSJG) {
        this.$toast.fail("请填写公示意见！")
        return
      }
      //获取第一条数据返回的CREATEDATE，计算该时间第二天凌晨和当前时间是否<=7天，如果<=7天且当前行X==330324000000提示：公示期未满七天，不允许往下一环节提交！（公示文件最后上传日期：' + CREATEDATE+ '），并且不允许往下一环节发送；否则正常发送
      let data = [{ "field": "house_cwgstj.TO_ROW_GUID", "value": this.rowData.TO_ROW_GUID }]
      const res = await GSA_Search('bbaf6141-ebb4-4b2d-ab50-39164281e672', data)
      if (res.Data.length > 0 && this.rowData.X == 330324000000) {
        //获取当前时间
        const nowday = this.timestampToTime(time.toLocaleString('en-US', { hour12: false }).split(" "))
        //处理创建时间
        const createdate = addDate(res.Data[0].CREATEDATE)
        const num = this.getDiffDay(createdate, nowday)
        if (num <= 7) {
          this.$toast.fail('公示期未满七天，不允许往下一环节提交!(公示文件最后上传日期：' + res.Data[0].CREATEDATE + ')')
          return false
        }
      }
      me.save("tj", function (i) {
        if (i) {
          me.$router.push({
            path: "/TreeSelect1",
            query: {
              data: me.rowData,
              iszjsh: 1,
            },
          });
        }
      });
    },
    save(p, callback) {
      //判断必填项
      if (this.formData.GSJG != "" && this.formData.GSJL != "") {
        this.formData.GSR = JSON.parse(
          window.localStorage.getItem("userName")
        ).userName;
        this.formData.GSSJ = this.nowTime;
        //this.formData.GSJL=this.GSJL;
        let params = {
          accessCode: "77ad6c1591e54d4fbc45ecc90374a2a2",
          cityCode: window.localStorage.getItem("citycode")
            ? window.localStorage.getItem("citycode")
            : "441300000000",
          params: {
            dataguid: "313d5ddd-2c1b-4f55-82e1-84d5effd9c47",
            strParams: JSON.stringify([this.formData]),
          },
        };
        QuerySignCallback(params);

        if (p == "tj") {
          callback(true);
        } else {
          this.$toast.success("保存成功!");
        }
      } else {
        this.$toast.success("请输入必填项!");
        if (p == "tj") {
          callback(false);
        }
      }
      //保存数据修改
    },
    Gotomap() {
      this.$router.push({
        path: "/mapContainer",
        query: {
          data: JSON.stringify(this.$route.query.data),
        },
      });
    },
    delectFile: async function (file) {
      let fileguid = "";
      if (file.ROW_GUID) {
        fileguid = file.ROW_GUID;
      } else {
        fileguid = this.fileGuid;
      }
      if (fileguid) {
        let params = {
          accessCode: "ce9b691634de4ebca68dc5bb638d07f4",
          cityCode: window.localStorage.getItem("citycode")
            ? window.localStorage.getItem("citycode")
            : "441300000000",
          params: {
            fileGuid: fileguid,
            token: window.localStorage.getItem("token"),
          },
        };
        const res = await FileServerProxy(params);
        let data = JSON.parse(res.data.data).Success;
        if (data) {
          this.$toast.success("删除成功!");
        }
      }
    },
    //获取相关材料
    getFile: async function () {
      let me = this;
      let groupGuid = [];
      me.fileData.forEach((item) => {
        groupGuid.push(item.groupGuid);
      });
      let params = {
        accessCode: "1fdcbce42c6d4748a020feba618d54b8",
        cityCode: window.localStorage.getItem("citycode")
          ? window.localStorage.getItem("citycode")
          : "441300000000",
        params: {
          groupGuid: groupGuid.join(","),
          toRowGuid: me.NewSPYJLisyt[0].ROW_GUID,
          token: window.localStorage.getItem("token"),
        },
      };
      const res1 = await FileServerProxy(params);
      let ress = JSON.parse(res1.data.data);
      if (ress.FilesInfo.length > 0) {
        ress.FilesInfo.forEach((element) => {
          me.fileData.forEach((item) => {
            if (element.GROUPGUID == item.groupGuid) {
              me.getFileUrl(element, item);
            }
          });
        });
      }
    },
    //获取附件文件流
    getFileUrl: async function (element, item) {
      let formData = new FormData();
      formData.append("accessCode", "98bcf528966e48ce896a8b3fd02d45d5");
      formData.append(
        "cityCode",
        window.localStorage.getItem("citycode")
          ? window.localStorage.getItem("citycode")
          : "441300000000"
      );
      formData.append(
        "paramStr",
        JSON.stringify({
          fileGuid: element.ROW_GUID,
        })
      );
      let response = await dataTransFilePreview(formData);
      if (response) {
        var img = new Blob([new Int8Array(response.data, 0)], {
          type: response.headers["content-type"],
        }); //type类型可自定义
        element["isImage"] = true;
        element["url"] = window.URL.createObjectURL(img);
        item.fileList.push(element);
      }
    },

    dataURLtoFile(dataurl, filename) {
      var arr = dataurl.split(","),
        mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]),
        n = bstr.length,
        u8arr = new Uint8Array(n);
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      return new File([u8arr], filename, { type: mime });
    },
    getBase64(data) {
      return new Promise((resolve, reject) => {
        const blob = new Blob([data], { type: "image/jpg" }); //类型一定要写！！！
        const reader = new FileReader();
        reader.readAsDataURL(blob);
        reader.onload = () => resolve(reader.result);
        reader.onerror = (error) => reject(error);
      });
    },
    afterRead(file) {
      this.getFileServerUpload(file.file);
    },
    getJFLYOpenDataView: async function () {
      this.CityColumns = [];
      let dataGuid = "84f533f1-d64e-4193-8c61-706aad255536";
      let searchObject = [];
      let token = window.localStorage.getItem("token");
      let params = {
        accessCode: "688bd3883572440a859dfd8ba9194e7b",
        // appKey: '6738b790-69e8-11ec-a673-6805cab640a0',
        cityCode: window.localStorage.getItem("citycode")
          ? window.localStorage.getItem("citycode")
          : "441300000000",
        params: {
          dataguid: dataGuid,
          searchObject: searchObject,
          token: token,
        },
      };
      const res = await QuerySignCallback(params);
      this.CityColumns = eval("(" + res.data.data + ")").Data;

    },
    onConfirmCity(value) {

      this.formData.GSJL = value.DICID;
      //   this.cityCode = value.CITYCODE;
      //   this.ValueCity = value.CITYNAME;
      this.showPickerC = false;
    },
    getFileServerUpload: async function (file) {
      debugger
      let data = {
        toRowGuid: this.NewSPYJLisyt[0].ROW_GUID,
        groupGuid: this.groupGuids,
        token: window.localStorage.getItem("token"),
      };
      let formData = new FormData();
      formData.append("file", file);
      formData.append("accessCode", "7a3fc061c866434b8475d3775c9ddcea");
      formData.append("cityCode", window.localStorage.getItem("citycode")
        ? window.localStorage.getItem("citycode")
        : "441300000000");
      formData.append("token", window.localStorage.getItem("token"));
      formData.append("paramStr", JSON.stringify(data));
      const res = await dataTransFile(formData);
      let data1 = JSON.parse(res.data.data).FileList;
      this.fileGuid = data1[0].FILEGUID;
      if (data1[0].FILEGUID) {
        this.$toast.success("上传成功!");
      }
    },
    //获取时间
    getTime() {
      let dateTime;
      let yy = new Date().getFullYear();
      let mm =
        new Date().getMonth() + 1 < 10
          ? "0" + (new Date().getMonth() + 1)
          : new Date().getMonth() + 1;
      let dd =
        new Date().getDate() < 10
          ? "0" + new Date().getDate()
          : new Date().getDate();
      let hh = new Date().getHours();
      let mf =
        new Date().getMinutes() < 10
          ? "0" + new Date().getMinutes()
          : new Date().getMinutes();
      let ss =
        new Date().getSeconds() < 10
          ? "0" + new Date().getSeconds()
          : new Date().getSeconds();
      dateTime = yy + "-" + mm + "-" + dd;
      this.nowTime = dateTime;
    },
    //获取数据
    getSPYJData: async function () {
      //调用存储过程来获取人员
      let I_ROWGUID = "'" + this.rowData.ROW_GUID + "'";
      let zjjbrextj = {
        procName: "up_query",
        dtParams: JSON.stringify([{ I_USERID: I_ROWGUID, I_TYPE: 3 }]),
        token: window.localStorage.getItem("token"),
      };
      let zgjbrfutj = {
        accessCode: "69db6bece3a7480592e2ec753d1e335e",

        cityCode: window.localStorage.getItem("citycode")
          ? window.localStorage.getItem("citycode")
          : "441300000000",
        params: zjjbrextj,
      };
      const reszgjbetj = await FileServerProxy(zgjbrfutj);
      // this.NewSPYJLisyt = JSON.parse(reszgjbetj.data.data);
      if (reszgjbetj.data.data && JSON.parse(reszgjbetj.data.data) && JSON.parse(reszgjbetj.data.data).Data.length > 0) {
        this.NewSPYJLisyt = JSON.parse(reszgjbetj.data.data).Data;
        debugger
        this.formData = this.NewSPYJLisyt[0];
        this.CityColumns.forEach(itemw => {
          if (itemw.DICID == this.formData.GSJL ? this.formData.GSJL : '48') {
            this.GSJL = itemw.DICNAME;
          }
        })
        if (!this.formData.GSJG) {
          this.formData.GSJG = '经七天公示，无异议'
        }
        this.getFile();
      }
    },
  },
  mounted() {
    //设置title
    if (ZWJSBridge) {
      ZWJSBridge.setTitle({
        title: "粤政易",
      })
        .then((res) => {
        })
        .catch((err) => {
        });
    }
    //获取
    this.getJFLYOpenDataView();
    //当前行数据
    ;
    if (this.$route.query.data) {
      this.rowData = JSON.parse(this.$route.query.data);
    }
    //获取意见回显数据，来修改数据
    this.getSPYJData();
    this.getTime();
  },
  updated() { },
};
</script>

<style lang="scss" scoped>
#piqianGS {
  height: 95vh;
  background: rgb(255, 255, 255);
  font-size: 18px;

  .content {
    width: 100%;
    height: calc(100% - 50px);
    overflow: auto;
    padding: 10px;

    .subTitle {
      width: 100%;
      height: 50px;
      line-height: 50px;
      font-size: 16px;
      position: relative;
      display: flex;
      align-items: center;
      border-bottom: 1px solid #9b9b9b;
      padding-left: 10px;

      .line {
        width: 6px;
        height: 26px;
        background: #3f8ffc;
        display: inline-block;
        margin-right: 10px;
      }
    }
  }

  .footer {
    text-align: center;
  }
}
</style>
<style lang="scss">
#piqianGS {
  .van-cell {}

  .van-cell--required::before {
    left: 0;
    font-size: 20px;
  }

  .van-field__label {
    color: black;
  }

  .GSJL {
    .van-field__control {
      text-align: right;
    }
  }
}
</style>
